#include <stdio.h>
#include <stdlib.h>
#include "StdTcp.h"
#include "StdThread.h"
#include "DoubleLinkList.h"

struct Message
{
    int flag;
    char fromName[20];
    char toName[20];
    char content[1024];
};

typedef struct Message Msg;

void *thread_handler(void *arg)//作为一个线程的入口函数，用于接收并处理 TCP 客户端接收到的消息
{
    TcpC *c = (TcpC *)arg;//arg 是传递给线程处理函数的参数，这里将其强制转换为 TcpC* 类型
    while (1)
    {
        Msg msg;
        TcpClientRecv(c, &msg, sizeof(msg));
        printf("recv from [%s]  message : %s\n", msg.fromName, msg.content);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("invaild numbers!\n");
        return -1;
    }
//argv[1] 是命令行参数中的第一个参数，表示服务器的 IP 地址或主机名。
    TcpC *c = InitTcpClient(argv[1], atoi(argv[2]));
    if (c == NULL)//atoi(argv[2]) 是将命令行参数中的第二个参数（作为字符串）转换为整数，表示服务器的端口号
    {
        printf("client point is NULL!\n");
        ClearTcpClient(c);
        return -1;
    }

    Msg msg;
    msg.flag = 1;
    printf("please input your name:\n");
    scanf("%[^\n]", msg.fromName);
    while (getchar() != '\n')
        ;

    TcpClientSend(c, &msg, sizeof(msg));

    Thread *t = InitThread(thread_handler, c);

    while (1)
    {
        printf("1.chat to one 2.broadcast\n");
        scanf("%d", &msg.flag);
        while (getchar() != '\n')
            ;
        msg.flag += 1;

        if (msg.flag == 2)
        {
            printf("please input your send to Name:\n");
            scanf("%[^\n]", msg.toName);
            while (getchar() != '\n')
                ;
            printf("please input your send content:\n");
            scanf("%[^\n]", msg.content);
            while (getchar() != '\n')
                ;
            TcpClientSend(c, &msg, sizeof(msg));
        }
        else
        {
            printf("please input your send content:\n");
            scanf("%[^\n]", msg.content);
            while (getchar() != '\n')
                ;
            TcpClientSend(c, &msg, sizeof(msg));
        }
    }

    ClearTcpClient(c);
    return 0;
}
